package com.quickcode.example.atomic;

import com.quickcode.annotation.Safe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * Created by 张波 on 2019/10/22.
 */
@Slf4j
@Safe
public class ExampleAtomic5 {

    /*原子更新一个类的实例对象值，必须要求通过volatile修饰并且非static类型*/
    private static AtomicIntegerFieldUpdater<ExampleAtomic5> updater = AtomicIntegerFieldUpdater.newUpdater(ExampleAtomic5.class,"count");

    @Getter
    public volatile int count = 100;

    public static void main(String[] args) {

        ExampleAtomic5 exampleAtomic5 = new ExampleAtomic5();

        if(updater.compareAndSet(exampleAtomic5,100,120)) {
            log.info("update success:{}" ,exampleAtomic5.getCount());
        }
        if(updater.compareAndSet(exampleAtomic5,100,200)) {
            log.info("update success:{}",exampleAtomic5.getCount());
        } else {
            log.info("update fail:{}",exampleAtomic5.getCount());
        }
    }

}
